package com.example.foo.api.web.product;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.ruoyi.common.core.domain.AjaxResult;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.product.model.Item;
import com.example.foo.product.query.ItemQuery;
import com.example.foo.product.service.ItemService;

@org.springframework.web.bind.annotation.RestController
public class ItemAction {

	private final ItemService itemService;

	public ItemAction(ItemService itemService) {
		this.itemService = itemService;
	}

	@GetMapping("/api/items")
	public AjaxResult index(ItemQuery itemQuery, Pageable pageable) {
		itemQuery.setState(Item.State.published);
		PageResult<Item> pageResult = itemService.findItems(itemQuery, pageable);
		return AjaxResult.successData(pageResult);
	}

	@GetMapping("/api/items/{id}")
	public AjaxResult showItem(@PathVariable("id") Long id) {
		Item item = itemService.findItemById(id);
		if (item == null) {
			return AjaxResult.error(404, "Not Found");
		}
		if (item.getState() != Item.State.published) {
			return AjaxResult.error(404, "Not Found");
		}
		return AjaxResult.successData(item);
	}

}
